package uk.ac.sanger.solr;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.biodas.jdas.exceptions.DASClientException;
import org.biodas.jdas.exceptions.ValidationException;

import org.biodas.jdas.schema.sources.CAPABILITY;
import org.biodas.jdas.schema.sources.COORDINATES;
import org.biodas.jdas.schema.sources.PROP;
import org.biodas.jdas.schema.sources.SOURCE;
import org.biodas.jdas.schema.sources.SOURCES;
import org.biodas.jdas.schema.sources.VERSION;
import org.biodas.jdas.schema.types.TYPE;
import org.springframework.web.client.RestTemplate;

public class CreateSolrSourcesIndexes {

    private final String nl;
    private final CreateSolrIndexerUtil util = new CreateSolrIndexerUtil();
    private final CreateSolrTypesIndexes typesIndexer = new CreateSolrTypesIndexes();

    public static void main(String[] args) {
        String homeDir = args[0];

        CreateSolrSourcesIndexes solr = new CreateSolrSourcesIndexes();
        solr.creatSolrIndexes(homeDir);
    }

    public CreateSolrSourcesIndexes() {
        nl = util.getLineSeperator();
    }

    public void creatSolrIndexes(String homeDir) {

//		if(!homeDir.endsWith("/")){
//			homeDir+=homeDir+"/";
//		}


        RestTemplate temp = new RestTemplate();
        String sourcesUrl="http://www.dasregistry.org/" + "das/sources/all";
        System.out.println("calling for sources at "+sourcesUrl);
        SOURCES sources = temp.getForObject(sourcesUrl, SOURCES.class);
        System.out.println("number of sources ="+sources.getSOURCE().size());
        File sourcesFile = new File(homeDir + "solrSources.xml");
        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(new FileOutputStream(sourcesFile), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            //  Auto-generated catch block
            e1.printStackTrace();
        } catch (FileNotFoundException e1) {
            //  Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("writing sources for solrIndexer at " + sourcesFile.getAbsolutePath());

        PrintWriter writer = null;
        writer = new PrintWriter(out);
        //NEED to add code to remove <a href from any fields!!!!
        writer.write("<add overwrite=\"true\" commitWithin=\"10000\">" + nl);
        for (SOURCE source : sources.getSOURCE()) {
            this.writeSolrSource(source, writer);
        	
        }
        writer.write("</add>");
        writer.flush();
        writer.close();

    }

    private void writeSolrSource(SOURCE source, PrintWriter out) {
        boolean doTypes = false;
        out.write("<doc>" + nl);
        createField(out, "website", "http://www.dasregistry.org");
        createField(out,"domain","Dasregistry");
        createField(out, "domain_url", "http://www.dasregistry.org/showdetails.jsp?auto_id=" + source.getUri());
        createField(out, "id", source.getUri());
        createField(out, "description", source.getDescription());
        createField(out, "title", source.getTitle());
        createField(out, "maintainer", source.getMAINTAINER().getEmail());
        createField(out, "docHref", source.getDocHref());
        for (VERSION version : source.getVERSION()) {
            createField(out, "version_uri", version.getUri());
            for (COORDINATES coords : version.getCOORDINATES()) {
                createField(out, "coord_uri", coords.getUri());
                createField(out, "coord_uri", coords.getAuthority());
                createField(out, "coord_source", coords.getSource());
                createField(out, "taxid", coords.getTaxid());
                createField(out, "coord_version", coords.getVersion());
                createField(out, "coord_content", coords.getContent());

            }
            for (CAPABILITY cap : version.getCAPABILITY()) {
                createField(out, "capability_type", cap.getType());
                if(cap.getType().equals("das1:types")){
                    doTypes=true;
                }
                createField(out, "query_uri", cap.getQueryUri());

            }
            for (PROP prop : version.getPROP()) {
                createField(out, prop.getName(), prop.getValue());
                //if (prop.getName().equals("types")) {
                 //   doTypes = true;
                //}
            }
        }
        //print out type information if it has a valid types document or specifies a types doc?
        if (doTypes) {
            try {
                
                    typesIndexer.writeSolrType(source, out);
                } catch (ValidationException ex) {
                    Logger.getLogger(CreateSolrSourcesIndexes.class.getName()).log(Level.SEVERE, null, ex);
                }
             catch (DASClientException ex) {
                Logger.getLogger(CreateSolrSourcesIndexes.class.getName()).log(Level.SEVERE, null, ex);
            }

        }


        out.write("</doc>" + nl);
    }

    private void createField(PrintWriter out, String name, String content) {
        util.createField(out, name, content);
    }
}
